<template>
    <div class="content">
        <cardBox class="left-wrapper" title="目录" icon="&#xe6f2;">
            <template #right>
                <el-select  @change="changeMenuSelModel" v-model="menuSelModel" placeholder="请选择" size="small" style="width:160px">
                  <el-option
                  v-for="(item,index) in menuSeloptions"
                  :key="index"
                  :label="item"
                  :value="item">
                  </el-option>
                </el-select>
            </template>
            <div>
                <el-select
                    v-model="searchId"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入搜索关键词"
                    :remote-method="remoteMethod"
                    style="width:290px;margin:10px"
                    @change="handleSearchName"
                    :loading="searchLoading"
                    size="small"
                    >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    <el-option
                    v-for="item in searchSelect"
                    :key="item.id"
                    :label="item.treeName"
                    :value="item.id">
                    </el-option>
                    <div slot="empty" class="empty-select">
                        <i class="iconfont">&#xe64a;</i>
                        <p>暂无匹配数据</p>
                    </div>
                </el-select>
                <MonitorTree :menuList="menuList" ref="treeMenu" @handleMenuClick="handleMenuClick" :expandedKeys="expandedKeys" v-loading="menuLoading" element-loading-text="目录加载中，请稍后"
                element-loading-spinner="el-icon-loading" @handleShowYQ="handleShowYQ" @handleShowXM="handleShowXM"/>
            </div>
        </cardBox>
        <div class="right-wrapper">
            <component
                :is="currentComponent"
                :stationId="stationId"
                :treeID="treeID"
                :CodeId="CodeId"
                :instRID="instR_ID"
                :showRoleAdd="permissions.showRoleAdd"
                :showRoleEdit="permissions.showRoleEdit"
                :showRoleCheck="permissions.showRoleCheck"/>
        </div>

        <!-- 弹窗部分 -->
         <el-dialog title="仪器信息" :visible.sync="yqDialogVisible" width="90%" v-dialogDrag :before-close="handleCloseYQDialog" class="instrument-dialog">
            <div>
                <el-tabs v-model="activeTabName" @tab-click="handleChangeTab">
                    <el-tab-pane label="埋设信息" name="1">
                        <span slot="label"><i class="iconfont">&#xe777;</i> 埋设信息</span>
                    </el-tab-pane>
                    <el-tab-pane label="率定信息" name="2">
                        <span slot="label"><i class="iconfont">&#xea44;</i> 率定信息</span>
                    </el-tab-pane>
                    <el-tab-pane label="采集频率" name="3">
                        <span slot="label"><i class="iconfont">&#xe73f;</i> 采集频率</span>
                    </el-tab-pane>
                </el-tabs>
            </div>
            
            <!-- 埋设信息 -->
            <div v-if="activeTabName == 1" class="tab-content">
                <instrumentTable :tableList="yqDialogTables" @afterPasete="afterPasete" @afterCellValueChange="afterCellValueChange" @cellDataChange="cellDataChange"                 :showRoleCheck="permissions.showRoleCheck"></instrumentTable>
            </div>
            
            <!-- 率定信息 -->
            <div v-if="activeTabName == 2" class="tab-content">
                <div class="operation-bar">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddPointList()" v-if="permissions.showRoleAdd">新增率定信息</el-button>
                </div> 
                <calibrationTable :tableData="instrumentData" :titleList="pointTitle" @edit="handleAddPointList" @del="handleDelPointList" :showRoleEdit="permissions.showRoleEdit" :showRoleDel="permissions.showRoleDel"></calibrationTable>
                <div class="point-title">关联POINT</div>
                <pointConcatDialog :pointList="pointList" @update="updatePoint" :modal="false"/>
            </div>
            
            <!-- 采集频率 -->
            <div v-if="activeTabName == 3" class="tab-content">
                <el-form :model="cjData" label-width="180px" class="frequency-form">
                <el-form-item label="测点名称">
                    <el-input v-model="cjData.pointName" placeholder="请输入" disabled>
                    <el-tooltip slot="suffix" content="测点名称不可编辑" placement="top">
                        <i class="el-icon-info"></i>
                    </el-tooltip>
                    </el-input>
                </el-form-item>
                <el-form-item label="采集频率(小时/次)" class="frequency-item">
                    <el-select v-model="cjData.hourFreq" placeholder="请选择" style="width: 100%">
                    <el-option v-for="i in 24" :key="i" :label="i" :value="i"></el-option>
                    </el-select>
                    <div class="form-tips">设置仪器每小时采集数据的次数</div>
                </el-form-item>
                <el-form-item label="采集时刻" v-if="cjData.hourFreq == 24" class="time-item">
                    <el-select v-model="cjData.hour" placeholder="请选择" clearable style="width: 100%">
                    <el-option v-for="i in 24" :key="i" :label="`${i}:00`" :value="i"></el-option>
                    </el-select>
                    <div class="form-tips">每天在指定时刻采集一次数据</div>
                </el-form-item>
                </el-form>
            </div>
            <div class="dialog-footer" v-if="activeTabName != '2'">
                <el-button @click="handleCloseYQDialog" size="small" icon="el-icon-circle-close" class="cancel-btn">取消</el-button>
                <el-button type="primary" @click="activeTabName == '3' ? handleSaveCjDialog() : handleSaveYQDialog()" size="small" icon="el-icon-circle-check" class="confirm-btn">保存配置</el-button>
            </div>
        </el-dialog>
        <calibrationAddDialog :pointFormLabel="pointFormLabel" :visible.sync="editCalibrationDialog" :pointForm="pointForm" :formulaList="formulaList" :pointNameList="pointNameList" isMonitor  @handleSavePoint="handleSavePoint"/>

        <PropertiesDialog :visible.sync="xmDialogVisible" :rightNodeInfo="rightNodeInfo" />
    </div>
</template>

<script>
import cardBox from "../../components/base/cardBox.vue";
import MonitorTree from '@/components/page/information/MonitorTree.vue'
import Overview from '@/components/page/information/Overview.vue'
import Foundation from '@/components/page/information/foundation.vue'
import Environment from '@/components/page/information/Environment.vue'
import {GetTreeStyle,GetTree,searchPointByName,GetInstrInformationInPage,setPowerPointBurys,PointQueryById,PointQueryPoint,GetFormulaByModeId,PointQueryByIdEdit,PointQueryByIdAdd,PointQueryByIdDel,getPointValves,QueryByCODE_ID,QueryByCODE_IDEdit} from "@/api/https";
import bus from '@/utils/eventBus.js';
import instrumentTable from '@/components/page/information/instrumentTable.vue'
import calibrationTable from '@/components/page/information/calibrationTable.vue'
import calibrationAddDialog from '@/components/page/information/calibrationAddDialog.vue'
import PropertiesDialog from '@/components/page/information/PropertiesDialog.vue'
import pointConcatDialog from '@/components/page/information/pointConcatDialog.vue'
import permissionMixin from '@/utils/permission'
import { debounce } from 'lodash';
import DateUtils from "@/utils/dateUtils";
export default ({
    name:'monitor',
    mixins: [permissionMixin],
    components:{MonitorTree,Overview,Foundation,Environment,cardBox,instrumentTable,calibrationTable,calibrationAddDialog,PropertiesDialog,pointConcatDialog},
    data() {
        return{
            menuSeloptions:[],
            menuSelModel:'',
            searchId:'',
            stationId:sessionStorage.getItem("stationId"),
            menuList:[],
            treeID:0,
            CodeId:0,
            isEnvironment:0,
            instR_ID:0,
            searchSelect:[],
            expandedKeys:[],
            selectedKey:null,
            menuLoading:false,
            yqDialogVisible:false,
            activeTabName:'1',
            yqDialogTables:[],
            tableFormList:[],
            instrumentData:[],
            pointFormLabel:[],
            pointTitle:[],
            editCalibrationDialog:false,
            pointForm:{},
            pointDialogEdit:false,
            Old_DT:'',
            formulaList:[],
            pointNameList:[],
            pointList:[],
            cjData:{},
            xmDialogVisible:false,
            rightNodeInfo:{},
            searchLoading:false,
            productTypeID:null
        }
    },
    created(){
        this.initBasin()
        this.GetTreeStyleData()
    },
    activated(){
        this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId != newStationId) {
            this.handleStationChanged(newStationId,this.$route.name);
        }
    },
    deactivated(){
       bus.$off('station-changed', this.handleStationChanged);
    },
    beforeDestroy(){
        if (this.$refs.treeMenu) {
            this.$refs.treeMenu = null;
        }
        this.cleanup();
    },
    computed: {
        currentComponent() {
            if (this.isEnvironment === 1) return Environment;
            // productTypeID：7测斜仪 200总览(Overview) 其它显示基本界面(Foundation) 
            if (!this.isEnvironment && this.productTypeID === 200) return Overview;
            if (!this.isEnvironment && this.productTypeID === 7) return null;
            if (!this.isEnvironment && this.productTypeID !== 200 && this.productTypeID !== 7) return Foundation;
            return null;
        },
        permissions() {
            return this.getPermissions() || {}
        }
    },
    methods:{
        initBasin() {
            bus.$emit('showBasin', true);
            bus.$off('station-changed', this.handleStationChanged);
            bus.$on('station-changed', this.handleStationChanged);
        },
        handleStationChanged(newStationId, targetRoute) {
             if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
                this.cleanup();
                this.GetTreeStyleData();
            }
        },
        cleanup(){
            this.menuSeloptions = []
            this.menuSelModel =''
            this.searchId = ''
            this.menuList = []
            this.expandedKeys = []
            this.selectedKey = null
            this.treeID = 0
            this.CodeId = 0
        },
        GetTreeStyleData(){
            this.menuLoading = true
            GetTreeStyle(this.stationId).then(res =>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.menuSeloptions = res.data || []
                    this.menuSelModel = res.data[0]
                    this.getTreeData()
                }else{
                    this.menuSeloptions = []
                    this.menuSelModel = ''
                    this.cleanup()
                }
            })
        },
        getTreeData(){
            GetTree(this.stationId,this.menuSelModel,this.searchId).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.menuList = res.data || []
                    this.$nextTick(()=>{
                        this.$refs.treeMenu.$refs.tree.setCurrentKey(0);
                        this.handleMenuClick(res.data[0])
                    })
                   this.menuLoading = false
                }else{
                    this.menuList = []
                    this.menuLoading = false
                }
            });
        },
        changeMenuSelModel(){
            this.menuLoading = true
            this.getTreeData()
        },
        handleSearchName(){
            this.menuLoading = true
            GetTree(this.stationId,this.menuSelModel,this.searchId).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    const  filter = res.data.filter(item=> { return item.navigationIDs !=null && item.navigationIDs.length > 0})
                    if(filter.length > 0){
                        const len = filter[0].navigationIDs.length
                        this.expandedKeys = filter[0].navigationIDs
                        this.selectedKey = filter[0].navigationIDs[len - 1]
                        
                        // 强制重置选中状态
                        this.$refs.treeMenu.$refs.tree.setCurrentKey(null);
                        this.$nextTick(() => {
                            this.setSelectedNode();
                        });
                    }
                }
                this.menuLoading = false
            });
        },
        setSelectedNode() {
            const tree = this.$refs.treeMenu.$refs.tree
            if (!tree) return;
            // 设置当前选中的节点
            tree.setCurrentKey(this.selectedKey);

            this.$nextTick(()=>{
                const container = this.$refs.treeMenu?.$refs.treeContainer;
                const selectedNode = tree.$el.querySelector('.is-current .el-tree-node__content');

                if (container && selectedNode) {
                    container.scrollTop = 0;
                    setTimeout(()=>{
                        const nodeRect = selectedNode.getBoundingClientRect();
                        const containerRect = container.getBoundingClientRect();
                        const relativeTop = nodeRect.top - containerRect.top + container.scrollTop;

                        container.scrollTo({
                            top: Math.max(0, relativeTop - 50), // 向上偏移50px，让节点不在最顶部
                            behavior: 'smooth',
                        });

                        const currentNode = tree.getNode(this.selectedKey);
                        if (currentNode) {
                            const nodeData = currentNode.data;
                            this.handleMenuClick(nodeData);
                        }
                    },200)
                }
            })
        },
        handleMenuClick(data){
            this.isEnvironment = data.node.ifEnvironment || 0
            this.treeID = data.node.treeid
            this.CodeId = data.node.codE_ID; 
            this.instR_ID = data.node.instR_ID 
            if(this.isEnvironment === 0){
                this.productTypeID = data.node.productTypeID
            }else{
                this.productTypeID = null
                this.CodeId = null;
            }
        },
        remoteMethod: debounce(function(query) {
            if (!query || query.trim() === '') {
                this.searchSelect = [];
                return;
            }
            
            this.searchLoading = true;
            searchPointByName(this.stationId, this.menuSelModel, query.trim())
                .then(res => {
                    if(res.isSuccess && res.data && res.data.length > 0){
                        this.searchSelect = res.data || [];
                    } else {
                        this.searchSelect = [];
                    }
                })
                .finally(() => {
                    this.searchLoading = false;
                });
        }, 300),
        handleShowYQ(data){
            this.rightNodeInfo = {...data}
            this.handleChangeTab()
            this.yqDialogVisible = true
        },
        handleShowXM(data){
            this.rightNodeInfo = {...data}
            this.xmDialogVisible = true
        },
        handleChangeTab(){
            if(this.tableFormList.length > 0){
                this.$confirm(`当前表格内容有修改尚未保存，是否要保存？`,'提示', {
                    confirmButtonText: '保存',
                    cancelButtonText: '不保存',
                    type: 'warning'
                }).then(() => {
                    setPowerPointBurys(this.tableFormList).then(res=>{
                        if(res.isSuccess){
                            this.$message.success('保存成功!')
                            this.tableFormList = []
                        }else{
                            this.$message.error(res.errorMessage)
                            this.activeTabName = 1
                        }
                    })
                }).catch(() => {
                   this.tableFormList = []
                });
            }
            const {treeid,statioN_ID,treeStyle,codE_ID} = this.rightNodeInfo.node
            if(this.activeTabName == '1'){
                GetInstrInformationInPage({
                    treeId:treeid,
                    statioN_ID:statioN_ID,
                    treeStyle:treeStyle,
                    pageIndex:1,
                    pageSize:50
                }).then(res=>{
                    if(res.isSuccess && res.data && res.data.node){ 
                        this.yqDialogTables = [...res.data.node] || []
                    }else{
                        this.yqDialogTables = []
                    }
                });
            }else if(this.activeTabName == '2'){
                PointQueryById({
                    treeId:treeid,
                    statioN_ID:statioN_ID,
                    treeStyle:treeStyle,
                    pageIndex:1,
                    pageSize:50
                }).then(res=>{
                    if(res.isSuccess){
                    if(res.data && res.data.data && res.data.data.length > 0){
                        const list = []
                        res.data.data.forEach((item,index)=>{
                        const a = {
                            codE_ID:item.codE_ID,
                            dt:item.dt,
                            pointName:item.pointName,
                            prefix:item.prefix,
                            rowKey:index++
                        }
                        if(item.params && item.params.length > 0){
                            item.params.forEach(subItem=>{
                                a[subItem.param] = subItem.value
                            })
                        }
                            list.push(a)
                        })
                        this.instrumentData = [...list]
                        }else{
                            this.instrumentData = []
                        } 

                        if(res.data && res.data.title && res.data.title.params){
                            this.pointTitle = res.data.title.params || []
                            const list = []
                            if(this.pointTitle.length > 0){
                                this.pointTitle.forEach(item=>{
                                    const data = {}
                                    data.key = item.param
                                    data.value = item.paramName
                                    list.push(data)
                                })
                                
                            }
                            this.pointFormLabel = [...list] 
                        }else{
                            this.pointFormLabel = []
                            this.pointTitle = []
                        }
    
                    } 
                })

                PointQueryPoint({
                    treeId:treeid,
                    statioN_ID:statioN_ID,
                    treeStyle:treeStyle,
                    pageIndex:1,
                    pageSize:50
                }).then(res =>{
                if(res.isSuccess && res.data){
                    this.pointNameList = res.data || []
                    if(res.data.length > 0){
                        GetFormulaByModeId(res.data[0].instrumentModelID).then(res1=>{
                            if(res1.isSuccess && res1.data){
                                this.formulaList = res1.data || []
                            }else{
                                this.formulaList = []
                            }
                        })
                    }
                }else{
                    this.pointNameList = []
                    this.formulaList = []
                }
            })
           this.updatePoint()
          }else if(this.activeTabName == '3'){
            QueryByCODE_ID({
                code_id:codE_ID
            }).then(res=>{
                if(res.isSuccess && res.data){
                    this.cjData = res.data || []
                }else{
                    this.cjData = {}
                }
            })
          }
        },
        updatePoint(){
            getPointValves({
              id:this.rightNodeInfo.node.id
            }).then(res=>{
                if(res.isSuccess && res.data){
                    this.pointList = res.data || []
                }else{
                    this.pointList = []
                }
            })
        },
        handleCloseYQDialog(){
            this.yqDialogVisible = false
            this.yqDialogTables = []
            this.tableFormList = []
            this.pointTitle = []
            this.instrumentData = []
            this.pointForm = {}
            this.pointDialogEdit = false
            this.Old_DT = ''
            this.cjData = {}
        },
        afterPasete(data){
            const start = data.selectionRangeIndexes.startRowIndex
            const end = data.selectionRangeIndexes.endRowIndex
            const filterList = [] //单元格自动填充后数据
            this.tableList.forEach((item,index)=>{
                if(index >= start && index <= end){
                    filterList.push(item)
                }
            })
            
            if(this.tableFormList.length > 0){
                let arr1 = this.tableFormList.filter(v => {
                    return filterList.every(e => e.id != v.id);
                });
                let arr2 = [...arr1,...filterList]
                this.tableFormList = [...arr2]
            }else{
                this.tableFormList = filterList
            }
        },
        afterCellValueChange(row){
            if(this.tableFormList.length > 0){
                const index = this.tableFormList.findIndex(item => item.id === row.id);
                if(index > -1){
                    this.tableFormList[index] = row
                }else{
                    this.tableFormList.push(row)
                }
            }
        },
        cellDataChange(row,type){
            if(type && type == 'monitor'){
                const text = this.PointMonitorList.filter(item=> {return item.text == row.monitorText})
                row.monitorID = text[0].id
            }
            if(this.tableFormList.length > 0){
                const index = this.tableFormList.findIndex(item => {return item.id == row.id})
                if(index > -1){
                    this.tableFormList[index] = row
                }else{
                    this.tableFormList.push(row)
                }
            }else{
                this.tableFormList.push(row)
            }
        },
        handleSaveYQDialog(){
            setPowerPointBurys(this.tableFormList).then(res=>{
                if(res.isSuccess){
                    this.$message.success('保存成功!')
                    this.handleCloseYQDialog()
                }else{
                    this.$message.error(res.errorMessage || '保存失败，请重试')
                }
            })
        },
        handleSaveCjDialog(){
            const _data = {
                ID:this.cjData.ID || 0,
                CODE_ID:this.rightNodeInfo.node.codE_ID,
                pointName:this.cjData.pointName || '',
                hourFreq:this.cjData.hourFreq || '',
                hour:this.cjData.hour || '',
                STATION_ID:this.stationId
            }
            QueryByCODE_IDEdit(_data).then(res=>{
                if(res.isSuccess){
                    this.handleCloseYQDialog()
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        },
        handleAddPointList(data){
            if(data){
                this.pointForm = {...data}
                this.pointDialogEdit = true
                this.Old_DT = data.dt
            }else{
                this.pointForm = {
                    dt:DateUtils.formatDate(DateUtils.getDate('today')),
                }
                this.pointDialogEdit = false
            }
            this.editCalibrationDialog = true
        },
        handleSavePoint(data){
            const _data = {},params = []
            for(let key in data){
                if(key.startsWith('Param')){
                    params.push({
                        param:key,
                        value:data[key],
                        paramName:''
                    })
                }else{
                    _data[key] = data[key]
                }
                _data.Old_DT = this.Old_DT || ''
                _data.params = params
                _data.pointName = this.pointNameList[0].pointName
                _data.CODE_ID = this.pointNameList[0].codE_ID
            }
            if(this.pointDialogEdit){
                _data.tp = 1
                PointQueryByIdEdit(_data).then(res =>{
                    this.saveCallback(res)
                })
            }else{
                _data.tp = 0
                _data.id = this.treeId
                PointQueryByIdAdd(_data).then(res =>{
                    this.saveCallback(res)
                })
            }
        },
        saveCallback(res){
            if(res.isSuccess){
                this.handleChangeTab()
                this.editCalibrationDialog = false
                this.pointForm = {}
                this.pointDialogEdit = false
                this.Old_DT =''
                this.formulaList = []
                this.pointNameList = []
            }else{
                this.$message.error(res.errorMessage)
            }
            
        },
        handleDelPointList(data){
            this.$confirm(`删除后不可恢复，确认删除该条数据?`,'提示',{
                type:'warning',
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                confirmButtonClass: 'el-button--danger',
            }).then(() => {
                PointQueryByIdDel({CODE_ID:data.codE_ID,DT:data.dt || ''}).then(res=>{
                    if(res.isSuccess){
                        this.$message.success("删除成功");
                        this.handleChangeTab()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {});  
        },
        
    }
})
</script>
<style lang="scss" scoped>
.content{
    display: grid;
    grid-template-columns: 310px 1fr;
    height: calc(100vh - 115px);
    .left-wrapper{
        width: 310px;
        height: calc(100vh - 115px);
        flex-shrink: 0;
        .tree-container{
            height: calc(100vh - 246px);
            overflow-y: auto;
            padding-right: 10px;
        }
    }
    .right-wrapper{
        height: calc(100vh - 115px);
        overflow: auto;
        margin: 0px 0 0 10px;
    }
}

// 弹窗
.instrument-dialog .el-dialog__body {
  padding: 15px 20px;
}

.dialog-header-tips {
  margin-bottom: 10px;
}

.tip-icon {
  color: #909399;
  margin-left: 5px;
  cursor: help;
}

.operation-bar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.operation-bar .el-button {
  margin-right: 10px;
}

.no-association {
  color: #f56c6c;
  font-size: 12px;
}

.frequency-form {
  padding: 10px 0;
}

.form-tips {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
.point-title{
    line-height: 60px;
    font-weight: bold;
}

</style>